package net.fpeg.kotlin.msa.wordbase.controller

import net.fpeg.kotlin.msa.wordbase.dto.WordUserRelationDto
import net.fpeg.kotlin.msa.wordbase.dto.WordUserRelationGroupIndexDto
import net.fpeg.kotlin.msa.wordbase.dto.WordUserRelationIndexDto
import net.fpeg.kotlin.msa.wordbase.service.WordUserRelationService
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.http.HttpStatus
import org.springframework.web.bind.annotation.*
import java.lang.Exception


@RestController
@RequestMapping("wordUserRelation")
class WordUserRelationController {
    @Autowired
    lateinit var wordUserRelationService: WordUserRelationService

    @PostMapping("/init/{wordValue}")
    @ResponseStatus(HttpStatus.CREATED)
    fun init(
            @RequestHeader("USER_ID") id: Long,
            @PathVariable wordValue: String
    ) = wordUserRelationService.init(id, wordValue)

    @GetMapping("/groups/{wordValue}")
    fun fetch(
            @RequestHeader("USER_ID") uid: Long,
            @PathVariable("wordValue") wordValue: String
    ) = WordUserRelationDto(
            wordUserRelationService.findGroup(uid, wordValue).map {
                WordUserRelationGroupIndexDto(
                        it.wordUserRelations?.map { relation ->
                            relation.run {
                                WordUserRelationIndexDto(
                                        id ?: throw Exception("未知错误"),
                                        word.value,
                                        wordUserRelationType.id ?: throw Exception("未知错误"),
                                        wordUserRelationType.value
                                )
                            }
                        } ?: listOf(),
                        it.id ?: throw Exception("未知错误")
                )
            }
    )

    @PostMapping("/{groupId}/{wordValue}/{typeId}")
    @ResponseStatus(HttpStatus.CREATED)
    fun add(
            @RequestHeader("USER_ID") uid: Long,
            @PathVariable("groupId") groupId: Long,
            @PathVariable("wordValue") wordValue: String,
            @PathVariable("typeId") typeId: Long
    ) = wordUserRelationService.add(uid, groupId, wordValue, typeId)

    @PutMapping("/{id}/{wordValue}/{typeId}")
    @ResponseStatus(HttpStatus.NO_CONTENT)
    fun edit(
            @RequestHeader("USER_ID") uid: Long,
            @PathVariable("id") id: Long,
            @PathVariable("wordValue") wordValue: String,
            @PathVariable("typeId") typeId: Long
    ) {
        wordUserRelationService.edit(uid, id, wordValue, typeId)
    }

    @DeleteMapping("/{id}")
    @ResponseStatus(HttpStatus.NO_CONTENT)
    fun remove(
            @RequestHeader("USER_ID") uid: Long,
            @PathVariable("id") id: Long
    ) {
        wordUserRelationService.remove(uid, id)
    }
}